<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="modelValue"
    @close="closeForm"
    draggable
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ dict.opera === "add" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar class="ba-table-form-scrollbar">
      <div
        class="ba-operate-form ba-add-form"
        :style="'width: calc(100% - ' + state.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="onAddSubmit(formRef)"
          :model="state.form"
          label-position="right"
          label-width="160px"
          :rules="rules"
        >
          <el-form-item label="字典项类型" prop="dictType">
            <el-input v-model="state.form.dictType" disabled />
          </el-form-item>
          <!-- <el-form-item label="字典编码" prop="dictCode">
            <el-input v-model="state.form.dictCode" />
          </el-form-item> -->
          <el-form-item label="字典项标签" prop="dictLabel">
            <el-input v-model="state.form.dictLabel" />
          </el-form-item>
          <el-form-item label="字典键值" prop="dictValue">
            <el-input v-model="state.form.dictValue" />
          </el-form-item>
          <el-form-item label="排序" prop="dictSort">
            <el-input
              v-model="state.form.dictSort"
              type="number"
              placeholder="请输入字典权重（排序依据）"
            ></el-input>
          </el-form-item>
          <FormItem
            label="字典状态"
            v-model="state.form.status"
            type="radio"
            :data="{
              content: {
                1: '停用',
                0: '正常',
              },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="state.form.remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              @keyup.enter.stop=""
              placeholder="备注"
            />
          </el-form-item>
        </el-form></div
    ></el-scrollbar>
    <template #footer>
      <div :style="'width: calc(100% - ' + state.labelWidth / 1.8 + 'px)'">
        <el-button @click="closeForm">取消</el-button>
        <el-button
          v-blur
          :loading="state.submitLoading"
          @click="onAddSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onBeforeUnmount, inject } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { useDictionary } from "@/store/backend/tool/dictionary";
import useCurrentInstance from "@/utils/useCurrentInstance";

const { proxy } = useCurrentInstance(); //mitt
const formRef = ref<FormInstance>();
const dict = useDictionary();
const dictOperation = inject("dictOperation") as any;

const state: {
  labelWidth: number;
  submitLoading: boolean;
  form: any;
} = reactive({
  labelWidth: 160,
  submitLoading: false,
  form: {},
});

interface Props {
  modelValue: boolean;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
});

const emits = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
}>();
const closeForm = () => {
  emits("update:modelValue", false);
};

const rules = reactive<FormRules>({
  dictCode: [{ required: true, message: "字典编码不能为空", trigger: "blur" }],
  dictLabel: [
    { required: true, message: "字典项标签不能为空", trigger: "blur" },
  ],
  dictType: [
    { required: true, message: "字典项类型不能为空", trigger: "blur" },
  ],
  dictValue: [{ required: true, message: "字典键值不能为空", trigger: "blur" }],
});

const onAddSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (valid) {
      if (dict.opera === "edit") {
        dict.editDictSet(state.form).then((res) => {
          dictOperation.updateDictionaryMoreTags(dict, dict.dictType); //更新字典moreTags
          closeForm();
          proxy.eventBus.emit("refreshDict");
        });
      } else {
        //新增
        dict.addDictSet(state.form).then((res) => {
          dictOperation.updateDictionaryMoreTags(dict, dict.dictType); //更新字典moreTags
          closeForm();
          proxy.eventBus.emit("refreshDict");
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

proxy.eventBus.on("editDict", (data: any) => {
  state.form = data;
  console.log("state.form", data);
});
proxy.eventBus.on("addDict", (data: any) => {
  state.form = data;
  console.log("state.form", data);
});
onMounted(() => {
  // state.form = dict.item;
});

onBeforeUnmount(() => {
  proxy.eventBus.off("editDict");
  proxy.eventBus.off("addDict");
});
</script>
<style lang="scss" scoped></style>
